function timeout(time) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve()
        }, time);
    })
}
class SuperTask {

    constructor(bingFaShuLiang = 2) {
        this.bingFaShuLiang = bingFaShuLiang
        this.tasks = []
        this.runningCount = 0
    }

    add(task) {
        return new Promise((resolve, reject) => {
            this.tasks.push({
                task,
                resolve, reject
            })
            this._run()
        })
    }

    _run() {
        while (this.runningCount < this.bingFaShuLiang && this.tasks.length) {
            const { task, resolve, reject } = this.tasks.shift()
            this.runningCount++
            Promise.resolve(task()).then(resolve, reject).finally(()=>{
                this.runningCount--
                this._run()
            })
        }
    }
}


const superTask = new SuperTask()

function addTask(time, name) {
    superTask.add(() => timeout(time)).then(() => {
        console.log(`任务${name}完成`);
    })
}
let index=0
setInterval(async() => {
    index++
    console.log(`当前是第${index}秒`)
}, 1000);

addTask(10000, 1)
addTask(5000, 2)
addTask(3000, 3)
addTask(4000, 4)
addTask(5000, 5)
